package com.warski.wonderfires.page.firedance;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import com.warski.wonderfires.BleActivity;
import com.warski.wonderfires.R;
import com.warski.wonderfires.TheApplication;

import static android.content.Context.BLUETOOTH_SERVICE;

/**
 * 初始页面
 */
public class DanceFragment extends Fragment {

    private TextView ipText;
    private boolean flag;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        flag = true;
        if (TheApplication.isConnection) {
            flag = false;
            Log.d("DanceFragment","onCreateView action_DanceFragment_to_FireDanceFragment");
            NavHostFragment.findNavController(DanceFragment.this).navigate(R.id.action_DanceFragment_to_FireDanceFragment);
        }
        View root = inflater.inflate(R.layout.fragment_dance, container, false);
        initView(root);

        if (mBluetoothAdapter == null) mBluetoothAdapter = initBluetoothAdapter();
        if (mScanCallback == null) mScanCallback = new ScanCallback();

        if (mHandler == null){
            mHandler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    ipText.setText(R.string.connection_ing);
                }
            };
        }

        // 延迟2s 设置配网状态
        mHandler.postDelayed(mRunnable,2000);
        return root;
    }

    private void initView(View root) {
        root.findViewById(R.id.titleLeft).setOnClickListener(v -> goToBle());

        ImageView appName = root.findViewById(R.id.app_name);
        appName.setImageResource(R.mipmap.app_name);

        ImageView fireImage = root.findViewById(R.id.fire_image);
        fireImage.setImageResource(R.mipmap.no_fire);

        ImageView minFireImage = root.findViewById(R.id.min_fire_image);
        minFireImage.setImageResource(R.mipmap.min_no_fire);

        ImageView maxFireImage = root.findViewById(R.id.max_fire_image);
        maxFireImage.setImageResource(R.mipmap.min_no_fire);

        ipText = root.findViewById(R.id.ip_text);
        // app运行如果是初次进入此界面，提示尝试连接，切换界面进入此界面提示检查连接
        if (TheApplication.isOpenApp) {
            ipText.setText(R.string.connection_ing);
            TheApplication.isOpenApp = false;
        }else {
            ipText.setTextColor(Color.WHITE);
            ipText.setText(R.string.check_connection);
        }
    }


    private Handler mHandler;
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mRunnable != null)
                mHandler.removeCallbacks(mRunnable);
            if (isAdapterEnabled()) {
                mBluetoothAdapter.startLeScan(mScanCallback);
                mHandler.postDelayed(this,8000);
            }

        }
    };


    public class ScanCallback implements BluetoothAdapter.LeScanCallback {

        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {

            String deviceName = "WonderFires";
            if (bluetoothDevice.getName() != null && bluetoothDevice.getName().contains(deviceName) && !bluetoothDevice.getAddress().contains("FF:FF:FF:FF")){
                if (mHandler != null) mHandler.sendEmptyMessage(12);
                if (mBluetoothAdapter != null) mBluetoothAdapter.stopLeScan(mScanCallback);
                String[] split = bluetoothDevice.getAddress().split(":");
                int[] ip = new int[4];
                for (int j = 0; j < 4; j++){
                    ip[j] = Integer.parseInt(split[j],16);
                }
                TheApplication.localGateIP = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];
                Log.d("TAG","run onLeScan");
                if (!TheApplication.isConnection) TheApplication.getInstance().connect();
                if (mHandler != null) mHandler.postDelayed(DanceFragment.this::setStatus,2000);
                }
        }
    }

    /**
     * 检查权限
     */
    private BluetoothAdapter mBluetoothAdapter;
    private ScanCallback mScanCallback;
    private boolean isAdapterEnabled() {
        if (BluetoothAdapter.getDefaultAdapter() ==null) return false;
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    private BluetoothAdapter initBluetoothAdapter() {
        BluetoothManager mBluetoothManager = (BluetoothManager) TheApplication.mContext.getSystemService(BLUETOOTH_SERVICE);
        return mBluetoothManager.getAdapter();
    }
    /**设置配网状态*/
    private void setStatus(){
        // 如果网络连接则切换连接成功界面
        if (TheApplication.isConnection && flag){
            flag = false;
            Log.d("DanceFragment","setStatus action_DanceFragment_to_FireDanceFragment");
            NavHostFragment.findNavController(DanceFragment.this).navigate(R.id.action_DanceFragment_to_FireDanceFragment);
        }else {
            // 没连接上提示连接失败
            /*ipText.setTextColor(Color.RED);
            ipText.setText(R.string.connection_fail);*/
            ipText.setText(R.string.connection_ing);
            mHandler.postDelayed(mRunnable,2000);
        }
    }
    /**跳转蓝牙配网界面*/
    private void goToBle() {
        Intent intent = new Intent(getContext(), BleActivity.class);
        startActivityForResult(intent, 200);
    }

    @Override
    public void onStop() {
        if (mBluetoothAdapter != null) mBluetoothAdapter.stopLeScan(mScanCallback);
        if (mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler.removeCallbacks(mRunnable);
        }
        super.onStop();
        Log.d("TAG","run onStop");
    }

    @Override
    public void onDestroy() {
        if (mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
            mHandler = null;
            Log.d("TAG","run onDestroy");
        }

        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 200) {
            // 如果网络连接则切换连接成功界面
            flag = true;
            if (TheApplication.isConnection){
                flag = false;
                NavHostFragment.findNavController(DanceFragment.this).navigate(R.id.action_DanceFragment_to_FireDanceFragment);
            }else {
                // 没连接上先提示检查连接，2s后再设置配网状态
                ipText.setTextColor(Color.WHITE);
                ipText.setText(R.string.check_connection);
            }
            new Handler().postDelayed(this::setStatus,2000);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
